package com.crocodileQ.filter;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.crocodileQ.domain.entity.LoginUser;
import com.crocodileQ.domain.entity.User;
import com.crocodileQ.enums.AppExceptionMsgEnum;
import com.crocodileQ.mapper.UserMapper;
import com.crocodileQ.utils.JwtUtil;
import com.crocodileQ.utils.WebUtil;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


@Component
public class AuthenticationTokenFilter extends OncePerRequestFilter {


//    @Autowired
//    private UserMapper userMapper;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        //获取token
        String token = request.getHeader("token");

        String uri = request.getRequestURI();
        if(uri.equals("/gate/logout")){
            filterChain.doFilter(request,response);
            return;
        }

        //放行未携带token 的请求，交由后面拦截器处理
        if (StrUtil.isBlank(token)) {
            filterChain.doFilter(request,response);
            return;
        }
        //解析token
        Claims claims;
        try {
            claims  = JwtUtil.parseJwt(token);
        } catch (Exception e) {
            //token无效
//            throw new AppException(AppExceptionMsgEnum.NEED_LOGIN);
            WebUtil.renderString(response,AppExceptionMsgEnum.NEED_LOGIN);
            return;
        }
        Long userId = Long.valueOf(claims.getSubject());

        //todo redis中查询LoginUser

        //暂时的操作，查询数据库
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getId,userId);
        User user = new User();
//        userMapper.selectOne(queryWrapper);

        if(BeanUtil.isEmpty(user)){
            //用户不存在
            WebUtil.renderString(response,AppExceptionMsgEnum.NEED_LOGIN);
            return;
        }

        //判断token
        LoginUser loginUser = new LoginUser();
        loginUser.setUser(user);
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginUser, null,null);

        //存储到SecurityContextHolder
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);

        //放行
        filterChain.doFilter(request,response);


    }
}

